<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/* * *
 * File: (Codeigniterapp)/libraries/Controllerlist.php
 * 
 * A simple library to list al your controllers with their methods.
 * This library will return an array with controllers and methods
 * 
 * The library will scan the "controller" directory and (in case of) one (1) subdirectory level deep
 * for controllers
 * 
 * Usage in one of your controllers:
 * 
 * $this->load->library('controllerlist');
 * print_r($this->controllerlist->getControllers());
 * 
 * @author Peter Prins 
 */

class ControllerList {

	/**
	 * Codeigniter reference 
	 */
	private $CI;

	/**
	 * Array that will hold the controller names and methods
	 */
	private $aControllers;
	private $loop = 0;

	// Construct
	function __construct() {
		// Get Codeigniter instance 
		$this->CI = get_instance();

		// Get all controllers 
		$this->setControllers(APPPATH . 'controllers/');
	}

	/**
	 * Return all controllers and their methods
	 * @return array
	 */
	public function getControllers() {
		return $this->aControllers;
	}

	/**
	 * Set the array holding the controller name and methods
	 */
//	public function setControllerMethods($p_sControllerName, $p_aControllerMethods) {
//		$this->aControllers[$p_sControllerName] = $p_aControllerMethods;
//	}

	/**
	 * Search and set controller and methods.
	 */
	private function setControllers($path) {

		$this->CI->load->helper('file');

		$files = get_dir_file_info($path, FALSE);
//		pr($files);die;
		foreach ($files as $file => $info) {
			
			$controller = $info['relative_path'] . $file;
			
			$controller = preg_replace('/.+(' . str_replace('/', '\/', preg_quote(APPPATH)). ')/', '$1', $controller);

			$controllername = basename($file, EXT);
						
			$ext = '.' . pathinfo(APPPATH . $controller, PATHINFO_EXTENSION);
			
			if ($ext != EXT)
				continue;
			
			if (!class_exists($controllername)) {
				$this->CI->load->file($controller);
			}
			
			// Add controller and methods to the array

			$aMethods = get_class_methods($controllername);
			
//			pr($aMethods);
			
			$aUserMethods = array();
			foreach ($aMethods as $method) {
				if (preg_match('/^_.+$/i', $method) == 0 && $method != 'get_instance' && $method != $controllername) {
					$aUserMethods[] = $method;
				}
			}
			$controllername = preg_replace('/' . str_replace('/', '\/', preg_quote(APPPATH . 'controllers/') . '(.+)' . preg_quote(EXT)) .'/', '$1', $controller);
			$this->aControllers[$controllername] = $aUserMethods;
//			} catch (Exception $e) {
//				show_error($e->getMessage());
//			}
		}
	}

}

// EOF